package com.ruoyi.common.utils.file;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.poi.util.IOUtils;

import java.io.*;
import java.nio.file.*;
import java.util.Enumeration;

public class ZipUtils {

    public static void unzipIfNotExists(String zipFilePath, String destDir) throws IOException {
        Path destPath = Paths.get(destDir);
        if (!Files.exists(destPath)) {
            Files.createDirectories(destPath);
            try (ZipFile zipFile = new ZipFile(zipFilePath)) {
                Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
                while (entries.hasMoreElements()) {
                    ZipArchiveEntry entry = entries.nextElement();
                    Path entryDestination = destPath.resolve(entry.getName());

                    if (entry.isDirectory()) {
                        Files.createDirectories(entryDestination);
                    } else {
                        Files.createDirectories(entryDestination.getParent());
                        try (InputStream in = zipFile.getInputStream(entry);
                             OutputStream out = Files.newOutputStream(entryDestination)) {
                            IOUtils.copy(in, out);
                        }
                    }
                }
            }
        }
    }
}
